package com.store.app.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.store.app.BaseActivity;
import com.store.app.ExitApplication;
import com.store.app.R;
import com.store.app.adapter.CouponAdapter;
import com.store.app.bean.CouponBean;
import com.store.app.bean.CouponUpdateBean;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.utils.SettingData;
import com.store.app.utils.UserTokenUtils;
import com.store.app.utils.Utils;
import com.store.app.widget.AutoListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * Created by Administrator on 2016/5/11.
 * 优惠券
 */
public class CouponNewActivity extends BaseActivity implements IOnHttpListener,View.OnClickListener {
    //    创建      验证
    private TextView tv_creat, tv_check;
    private TextView tv_title;
    private AutoListView lv_coupons;
    private NetRequest netRequest;
    private ImageView img_fail_nonet;
    private ImageView img_fail_notext;
    private TextView tv_fail;
    private Map<String, String> map = new HashMap();
    private LinearLayout lin_loadNull;//加载为空
    private LinearLayout lin_loadfail;  //无网络页面
    private TextView tvReload;
    private int pageNum = 1;
    private RelativeLayout loadfail;//加载状态背景
    private CouponAdapter couponAdapter;
    private List<CouponBean> couponBeanList;
    private LinearLayout ll_cash_get;
    private LinearLayout ll_free_get;
    private RelativeLayout rl_dialog_view;
    public void showLoadResult(int state) {
        //无网络情况
        if (state == 1) {
            loadfail.setVisibility(View.VISIBLE);
            lin_loadfail.setVisibility(View.VISIBLE);
            lin_loadNull.setVisibility(View.GONE);
        }//无数据情况
        else if (state == 2) {
            loadfail.setVisibility(View.VISIBLE);
            lin_loadfail.setVisibility(View.GONE);
            Log.v("zyl", "加载内容为空");
            lin_loadNull.setVisibility(View.VISIBLE);
        }//都不显示
        else {
            loadfail.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ExitApplication.getInstance().addActivity(this);
        setContentView(R.layout.activity_coupon_new);
        initView();
        initData();
        initListeners();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void initData() {
        couponBeanList = new ArrayList<CouponBean>();
        UserTokenUtils.setUerToken(this);
        netRequest = new NetRequest(this);
        couponAdapter = new CouponAdapter(this,couponBeanList);
        lv_coupons.setAdapter(couponAdapter);

        netRequest.requestCouponFind(2);

    }

    private void initListeners() {
        lv_coupons.setOnRefreshListener(new AutoListView.OnRefreshListener() {

            @Override
            public void onRefresh() {
                netRequest.requestCouponFind(1);
            }
        });

        tv_creat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rl_dialog_view.setVisibility(View.VISIBLE);
            }
        });
        tv_check.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(CouponNewActivity.this, ValidateCouponActivity.class);
                startActivity(intent);
            }
        });
        findViewById(R.id.public_ll_return).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tvReload = (TextView) findViewById(R.id.tv_reload);
        tvReload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Utils.isFastClick()) {
                    return;
                }
                if (lv_coupons != null){
                    couponBeanList.clear();
                    couponAdapter.notifyDataSetChanged();
                    netRequest.requestCouponFind(1);
                }
            }
        });

        lv_coupons.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position >= 1) {
                    CouponBean couponBean = couponBeanList.get(position - 1);
                    Log.v("zyl", "couponBean==" + (couponBean == null));
                    if(couponBean!=null){
                        int kucun = 0;
                        try {
                            int faxing = Integer.parseInt(couponBean.getIssued_num());
                            int lingqu = Integer.parseInt(couponBean.getUsed_num());
                             kucun = faxing - lingqu;
                        }catch (Exception e){
                            kucun = 0;
                        }
                        Log.v("zyl","优惠券 kucun："+kucun);
                        String s_cate = couponBean.getCategory_id();
                        Log.v("zyl","couponBean.getStatus():"+couponBean.getStatus());
                        if (SettingData.Post_AddCoupons1.equals(s_cate)) {//现金购买型
                            if("off_shelf".equals(couponBean.getStatus())){
                                Intent intent = new Intent(CouponNewActivity.this,AddCoupons1_RebuildActivity.class);
                                intent.putExtra("item_id", couponBean.getItem_id());
                                startActivity(intent);
                            }else {
                                Intent intent = new Intent(CouponNewActivity.this, AddCoupons1Activity.class);
                                intent.putExtra("item_id", couponBean.getItem_id());
                                intent.putExtra("kucun",kucun);
                                startActivity(intent);
                            }
                        }  else if (SettingData.Post_AddCoupons3.equals(s_cate)) {//免费领取型
                            if("off_shelf".equals(couponBean.getStatus())){
                                Intent intent = new Intent(CouponNewActivity.this,AddCoupons3_RebuildActivity.class);
                                intent.putExtra("item_id", couponBean.getItem_id());
                                startActivity(intent);
                            }else {
                                Intent intent = new Intent(CouponNewActivity.this, AddCoupons3Activity.class);
                                intent.putExtra("item_id", couponBean.getItem_id());
                                intent.putExtra("kucun",kucun);
                                startActivity(intent);
                            }
                        }
                    }

                }
            }
        });
    }

    private void initView() {
        loadfail = (RelativeLayout) findViewById(R.id.loadfail);
        tv_creat = (TextView) findViewById(R.id.oneyuanbuy_btn1);
        tv_check = (TextView) findViewById(R.id.oneyuanbuy_btn2);
        tv_title = (TextView) findViewById(R.id.tvTitle);
        tv_title.setText("优惠券");
        lv_coupons = (AutoListView) findViewById(R.id.onebuy_listview);
        lin_loadfail = (LinearLayout) findViewById(R.id.ll_load_fail);//无网络
        lin_loadNull = (LinearLayout) findViewById(R.id.ll_load_null);//无数据
        loadfail.setVisibility(View.GONE);
        img_fail_nonet = (ImageView) findViewById(R.id.loadfail_nonet);
        img_fail_notext = (ImageView) findViewById(R.id.loadfail_notext);
        tv_fail = (TextView) findViewById(R.id.loadfail_tv);
        ll_cash_get = (LinearLayout) findViewById(R.id.ll_cash_get);
        ll_cash_get.setOnClickListener(this);
        ll_free_get = (LinearLayout) findViewById(R.id.ll_free_get);
        ll_free_get.setOnClickListener(this);
        rl_dialog_view = (RelativeLayout) findViewById(R.id.rl_dialog_view);
        rl_dialog_view.setOnClickListener(this);
    }

    @Override
    public void onAfinalFail() {
        lv_coupons.setLoadEnable(false);
        lv_coupons.onRefreshComplete();
        showLoadResult(1);
    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        if(requestId==1){
            lv_coupons.onRefreshComplete();
            try {
                JSONObject jsonObject = new JSONObject(result);
                JSONArray jsonArray = jsonObject.getJSONArray("list");
                Gson gson =new Gson();
                couponBeanList.clear();
              //  Map<String, Object> urlMap = GsonUtil.jsonToMap(jsonObject.getString("doc_url"));
                for (int i =0 ;i<jsonArray.length();i++){
                    String listItem = jsonArray.getString(i);
                    CouponBean couponBean = gson.fromJson(listItem, CouponBean.class);
//                    String picURL = couponBean.getPic_path();
//                    if(!TextUtils.isEmpty(picURL)){
//                        //说明有两张图片
//                        if(picURL.contains(",")){
//                            couponBean.setUrl1(urlMap.get( picURL.split(",")[0]).toString());
//                            couponBean.setUrl2(urlMap.get(picURL.split(",")[1]).toString());
//                        }else{
//                            couponBean.setUrl1(urlMap.get( picURL).toString());
//                        }
//                    }
                    couponBeanList.add(couponBean);
                }
                couponAdapter.notifyDataSetChanged();
                if(couponBeanList.size()==0){
                    showLoadResult(2);
                }else{
                    showLoadResult(3);
                }
            }catch (JSONException e){
                e.printStackTrace();
                showLoadResult(1);
            }
        }else if(requestId==2){
            lv_coupons.setLoadEnable(false);
            try {
                JSONObject jsonObject = new JSONObject(result);
                JSONArray jsonArray = jsonObject.getJSONArray("list");
                Gson gson =new Gson();
                couponBeanList.clear();
              //  Map<String, Object> urlMap = GsonUtil.jsonToMap(jsonObject.getString("doc_url"));
                for (int i =0 ;i<jsonArray.length();i++){
                    String listItem = jsonArray.getString(i);
                    CouponBean couponBean = gson.fromJson(listItem, CouponBean.class);
//                    String picURL = couponBean.getPic_path();
//                    if(!TextUtils.isEmpty(picURL)){
//                        //说明有两张图片
//                        if(picURL.contains(",")){
//                            couponBean.setUrl1(urlMap.get( picURL.split(",")[0]).toString());
//                            couponBean.setUrl2(urlMap.get(picURL.split(",")[1]).toString());
//                        }else{
//                            couponBean.setUrl1(urlMap.get( picURL).toString());
//                        }
//                    }
                    couponBeanList.add(couponBean);
                }
                couponAdapter.notifyDataSetChanged();
                if(couponBeanList.size()==0){
                    showLoadResult(2);
                }else{
                    showLoadResult(3);
                }

            }catch (JSONException e){
                showLoadResult(1);
                e.printStackTrace();
            }
        }

    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        showLoadResult(1);
        if(requestId==1){
            lv_coupons.onRefreshComplete();
        }else if(requestId==2){
            lv_coupons.setLoadEnable(false);
        }

    }

    public void onEvent(CouponUpdateBean event) {
        if(event.type==1){
            netRequest.requestCouponFind(2);
            try {
                lv_coupons.setSelection(1);
            }catch (Exception e){

            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            //现金领取型
            case R.id.ll_cash_get:
                rl_dialog_view.setVisibility(View.GONE);
                Intent intentToCase = new Intent (CouponNewActivity.this,AddCoupons1Activity.class);
                startActivity(intentToCase);
                break;
            //免费领取型
            case R.id.ll_free_get:
                rl_dialog_view.setVisibility(View.GONE);
                Intent intentToFree= new Intent (CouponNewActivity.this,AddCoupons3Activity.class);
                startActivity(intentToFree);
                break;
            case R.id.rl_dialog_view:
                rl_dialog_view.setVisibility(View.GONE);
                break;
        }
    }

    @Override
    public void finish() {
        if(rl_dialog_view.getVisibility()==View.VISIBLE){
            rl_dialog_view.setVisibility(View.GONE);
            return;
        }
        super.finish();
    }
}
